package v1

import (
	"github.com/gin-gonic/gin"
	"maya-service/bll"
	"maya-service/model"
	"maya-service/server/web/middleware"
	"maya-service/utils"
)

var SupervisorOrder = &supervisorOrder{}

func init() {
	RegisterRouter(SupervisorOrder)
}

type supervisorOrder struct{}

// Init
func (a *supervisorOrder) Init(r *gin.RouterGroup) {
	g := r.Group("/supervisorOrder", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
}

// create
func (a *supervisorOrder) create(c *gin.Context) {
	var (
		in  = &model.SupervisorOrderCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.SupervisorOrder.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update
func (a *supervisorOrder) update(c *gin.Context) {
	var (
		in  = &model.SupervisorOrderUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.SupervisorOrder.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *supervisorOrder) list(c *gin.Context) {
	var (
		in  = &model.SupervisorOrderListRequest{}
		out = &model.SupervisorOrderListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.SupervisorOrder.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}

	var ids []string
	for i := 0; i < len(out.List); i++ {
		ids = append(ids, out.List[i].SupervisorId)
	}

	listMap, _ := bll.GetUserInfoList(c.Request.Context(), ids)
	for i := 0; i < len(out.List); i++ {
		if v, ok := listMap[out.List[i].SupervisorId]; ok {
			out.List[i].SupervisorName = v.UserName
		}
	}

	utils.ResponseOk(c, out)
}

// list
func (a *supervisorOrder) find(c *gin.Context) {
	var (
		in  = &model.SupervisorOrderInfoRequest{}
		out = &model.SupervisorOrderInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.SupervisorOrder.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// delete
func (a *supervisorOrder) delete(c *gin.Context) {
	var (
		in  = &model.SupervisorOrderDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.SupervisorOrder.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
